package com.niiwoo.civet.account.service.local.openAccount2.listener;

import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.account.constant.MQConstant;
import com.niiwoo.civet.account.dao.entity.BankCard;
import com.niiwoo.civet.account.dao.entity.OpenAccountRecord;
import com.niiwoo.civet.account.dao.mapper.BankCardMapperExt;
import com.niiwoo.civet.account.dto.request.UserIdentityDataMQDTO;
import com.niiwoo.civet.account.enums.AccountTypeEnum;
import com.niiwoo.civet.account.enums.OpenAccountMajorWay;
import com.niiwoo.civet.account.enums.OpenAccountRecordStatusEnum;
import com.niiwoo.civet.account.enums.OpenAccountWayEnum;
import com.niiwoo.civet.account.service.local.openAccount2.dto.OpenAccountEvent;
import java.util.Arrays;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Component
public class UserIdentityListener implements OpenAccountListener {


    private final List<OpenAccountMajorWay> INTERESTED_WAY_LIST = Arrays.asList(OpenAccountMajorWay.PERSON_BIND_BANK_CARD_REGISTER, OpenAccountMajorWay.ACTIVATE);

    private final OpenAccountRecordStatusEnum EXCEPT_STATUS = OpenAccountRecordStatusEnum.SUCCESS;

    @Autowired
    BankCardMapperExt bankCardMapperExt;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Transactional(isolation = Isolation.READ_COMMITTED)
    @Override
    public void handle(OpenAccountEvent event) {
        OpenAccountRecord record = event.getRecord();
        BankCard bankCard = bankCardMapperExt.selectSimpleUserBankCard(record.getUserId());
        // 银行卡账户为空不处理
        if (bankCard == null) {
            log.error("初次开户成功###同步二要素到用户中心，银行卡为空");
            return;
        }
        // 不处理企业用户信息
        if (AccountTypeEnum.ENTERPRISE.getValue().equals(bankCard.getAccountType())) {
            log.info("初次开户成功###同步二要素到用户中心，企业用户不处理");
            return;
        }
        UserIdentityDataMQDTO identityDataMQDTO = new UserIdentityDataMQDTO();
        identityDataMQDTO.setUserId(record.getUserId());
        identityDataMQDTO.setName(bankCard.getRealName());
        identityDataMQDTO.setIdCardNo(bankCard.getIdCard());
        log.info("初次开户成功###同步二要素到用户中心, data={}", JSON.toJSONString(identityDataMQDTO));
        rabbitTemplate.convertAndSend(MQConstant.UC_IDENTITY_EXCHANGE, MQConstant.UC_IDENTITY_DATA_ROUTING, identityDataMQDTO);
    }

    @Override
    public boolean isExpectStatus(OpenAccountRecordStatusEnum status) {
        return EXCEPT_STATUS == status;
    }

    @Override
    public boolean isInterestedOpenAccountWay(OpenAccountWayEnum way) {
        return INTERESTED_WAY_LIST.contains(way.getMajor());
    }

}
